package com.zoro.barn.commons.webcommons.webconfig;

import com.zoro.barn.commons.foundation.exceptions.BusinessException;
import com.zoro.barn.commons.webcommons.exceptions.DefaultExceptionHandler;
import com.zoro.barn.commons.foundation.exceptions.PayloadBusinessException;
import com.zoro.barn.commons.webcommons.response.entity.BarnResponseEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author zhaoxingwu
 */
public class ExceptionHandlerConfig {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    private final DefaultExceptionHandler handler = new DefaultExceptionHandler();


    @Bean("barnExceptionHandler")
    public NestedExceptionHandler responseBodyAdvice() {
        logger.info(" default exception handler loaded!");
        return new NestedExceptionHandler();
    }


    @RestControllerAdvice
    private class NestedExceptionHandler {


        @ExceptionHandler(Exception.class)
        public ResponseEntity<BarnResponseEntity<?>> handler(Exception e) {
            if (e instanceof PayloadBusinessException) {
                return handler.businessExceptionHandler((PayloadBusinessException) e);
            } else if (e instanceof BusinessException) {
                return handler.businessExceptionHandler((BusinessException) e);
            }
            return handler.exceptionHandler(e);
        }
    }
}
